package com.liusuai.yixian.utils;

import com.liusuai.yixian.update.DownloadControler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(DownloadControler.class);

    public static void downloadFile(File file, HttpServletResponse response) {
        response.resetBuffer();
        response.reset();
        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        // 下载文件能正常显示中文
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

            // 实现文件下载
            byte[] buffer = new byte[1024];


            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            logger.info("Download is successfully!");
        } catch (Exception e) {
            logger.error("Download is failed!" + e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
